package com.whately.core.base.config;

import com.whately.core.base.constant.ConstantByOS;
import com.whately.core.base.constant.ConstantProject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;

/**
 * WebMvcConfigurationSupport 替代 WebMvcConfigurerAdapter
 *
 * https://www.cnblogs.com/unknows/p/10620685.html
 */
@Configuration
public class WhatelyWebAppConfigurer implements WebMvcConfigurer {

    private final Logger logger = LoggerFactory.getLogger(WhatelyWebAppConfigurer.class);

    public static final String API_REQUEST_PATH_MATCHER = "/api/**";

    public static final String SWAGGER_UI_URL_CSRF = "/csrf";

    public static final String[] SWAGGER_UI_EXCLUDE_URLS = { "/v2/**", "/swagger-ui.html","/webjars/**",SWAGGER_UI_URL_CSRF+"/**", "/swagger-resources/**"};

    public static final String[] DEFAULT_EXCLUDE_URLS ;

    static{
        String[] tmpUrlArrays = {"/","/favicon.ico","/*.html","/error","/static/**"};
        DEFAULT_EXCLUDE_URLS = new String[tmpUrlArrays.length+SWAGGER_UI_EXCLUDE_URLS.length];
        int i=0;
        for(String str:tmpUrlArrays){
            DEFAULT_EXCLUDE_URLS[i] = str;
            i++;
        }

        int initLength = DEFAULT_EXCLUDE_URLS.length;
        for(String str:SWAGGER_UI_EXCLUDE_URLS){
            DEFAULT_EXCLUDE_URLS[i] =str;
            i++;
        }
    }
    @Autowired
    private HttpMessageConverter fastJsonHttpMessageConverter;

    @Autowired
    private ConstantByOS constantByOS;


    /**
     * 初始页面
     * @param
     */
    /*@Override
    public void addViewControllers(ViewControllerRegistry registry ) {
        registry.addViewController("/").setViewName( "forward:/index.html" );
        registry.setOrder( Ordered.HIGHEST_PRECEDENCE );
        super.addViewControllers(registry);
    }*/

    /**
     * 参数注册
     */
    /*@Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        super.addArgumentResolvers(argumentResolvers);
        argumentResolvers.add(new StringToPureStringResolver());
    }*/

    /**
     * 参数转换
     * 字符串净化
     */
    /*@Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new StringToPureStringConverter());
    }*/


    /**
     * 自定义静态资源路径
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations(ResourceUtils.CLASSPATH_URL_PREFIX+"/static/");

        registry.addResourceHandler("/resourceFile/**").
                addResourceLocations(ResourceUtils.FILE_URL_PREFIX+constantByOS.getSaveDir());

        registry.addResourceHandler("/swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

    }

    /**
     * 对于前后端分离的项目来说，如果前端项目与后端项目部署在两个不同的域下，
     * 那么势必会引起跨域问题的出现。
     * 跨域处理 映射所有路径 允许所有来源 以下方法请求
     * @param
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedHeaders("*")
                .exposedHeaders(HttpHeaders.SET_COOKIE, ConstantProject.response_header_token_name)
                .allowedMethods("GET", "POST", "PUT", "OPTIONS", "DELETE", "PATCH")
                .maxAge(3600);
    }

    /**
     * 保证StringHttpMessageConverter在FastJsonHttpMessageConverter前被调用
     * 参考 https://blog.csdn.net/john1337/article/details/88847260
     * @param converters
     */
    @Override
   public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //重新设置StringHttpMessageConverter字符集为UTF-8，解决中文乱码问题
        // 使用 utf-8 编码集的 conver 替换默认的 conver（默认的 string conver 的编码集为"ISO-8859-1"）
        Iterator<HttpMessageConverter<?>> iterator = converters.iterator();
        while (iterator.hasNext()) {
            HttpMessageConverter<?> converter = iterator.next();
            if (converter instanceof StringHttpMessageConverter) {
                iterator.remove();
            }
        }

        converters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));

        //1.需要定义一个convert转换消息的对象;

        converters.add(fastJsonHttpMessageConverter);
    }


}
